import cv2
import matplotlib.pyplot as plt
import numpy as np
import math

def rotate_2d(points, theta, cx=0, cy=0):
    # 创建旋转矩阵
    rotation_matrix = np.array([
        [np.cos(theta), -np.sin(theta)],
        [np.sin(theta), np.cos(theta)]
    ])
    
    # 平移到点(cx, cy)，旋转，然后平移回原来的位置
    translated_points = points - np.array([[cx], [cy]])
    rotated_points = np.dot(translated_points, rotation_matrix.T)
    final_points = rotated_points + np.array([[cx], [cy]])
    
    return final_points

src_list=[]
X=[]
Y=[]
def click_event(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        print(x, ',',y)
        src_list.append((x,y))
        X.append(x)
        Y.append(y)
        font = cv2.FONT_HERSHEY_SIMPLEX
        strXY = str(x) + ', '+ str(y)
        cv2.putText(img, strXY,(x,y), font, 0.3,(255,255,0),1)
        cv2.imshow('image', img)
cv2.namedWindow('image',0)
img = cv2.imread("./a.png",1)  #读取图片
cv2.imshow('image',img)
cv2.setMouseCallback('image',click_event)
cv2.waitKey(0)
cv2.imwrite('./point_param.jpg',img)
cv2.destroyAllWindows()
rows,cols = img.shape[:2]
#第一个参数旋转中心，第二个参数旋转角度，第三个参数：缩放比例
angle_=-math.atan((X[1]-X[0])/(Y[1]-Y[0]))*180/3.14
angle=-math.atan((X[1]-X[0])/(Y[1]-Y[0]))
M = cv2.getRotationMatrix2D((np.sum(X)/4,np.sum(Y)/4),angle_,1)
#第三个参数：变换后的图像大小
res = cv2.warpAffine(img,M,(cols,rows))


#标记点跟着旋转
center = np.array([np.sum(X)/4,np.sum(Y)/4])
# 多个二维点
points = np.array(src_list)
# 定义旋转矩阵
rotation_matrix = np.array([[np.cos(-angle), -np.sin(-angle)],[np.sin(-angle), np.cos(-angle)]])
# 计算每个点相对于中心点的坐标
centered_points = points - center
# 进行点的旋转
rotated_points = np.dot(rotation_matrix, centered_points.T).T + center
print("原始点:")
print(points)
print("旋转后的点:")
print(rotated_points)



#图像全屏显示
pts1 = np.float32(rotated_points)  #原始图像四个顶点
rp=np.matrix.tolist(rotated_points)
x,y=zip(*rp)
row=max(x)-min(x)
col=max(y)-min(y)
pts2 = np.float32([[0, 0], [0,col], [row, col], [row, 0]]) #转换目标点
matrix = cv2.getPerspectiveTransform(pts1, pts2)
res2 = cv2.warpPerspective(res, matrix, (int(row),int(col))) #透视变换

plt.subplot(131)
plt.imshow(img)
plt.subplot(132)
plt.imshow(res)
plt.subplot(133)
plt.imshow(res2)
cv2.namedWindow("result",cv2.WINDOW_AUTOSIZE)    #创建GUI窗口,形式为自适应
cv2.imshow("result",res2)
cv2.namedWindow("image",cv2.WINDOW_AUTOSIZE)    #创建GUI窗口,形式为自适应
cv2.imshow('image',img)
cv2.waitKey(0)